package com.lnu.information.controller;

import com.lnu.information.dto.RequestDTO;
import com.lnu.information.util.SpirePdfUtil;
import com.lnu.information.util.Video2AudioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;

/**
 * @author : jian.zhang-2
 * @description:
 * @date : Create in 3:51 PM 2022/2/20
 * @modified By :
 */
@RestController
@Api("Swagger相关测试API")
@RequestMapping("/convert")
public class FileController {

    @RequestMapping("/hello")
    public String index(){
        return "home";
    }

    @ApiOperation(value = "图片转文本")
    @ResponseBody
    @PostMapping("/Image2Text")
    public String Image2Text(@RequestBody RequestDTO requestDTO){
        try {
            File sourceFile = new File(requestDTO.getFilePath());
            SpirePdfUtil image2Text = new SpirePdfUtil();
            String result = image2Text.image2Txt(sourceFile);
            String targetFilePath = sourceFile.getAbsolutePath().substring(0, sourceFile.getAbsolutePath().lastIndexOf(".")) + ".txt";
            FileWriter writer = new FileWriter(targetFilePath);
            writer.write(result);
            writer.flush();
            writer.close();
            String sourceFileName = sourceFile.getName();
            sourceFile.delete();
            return sourceFileName + "转换成功，文本存储在 " + targetFilePath + "中";
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常，则告诉页面失败
            return "转换失败";
        }
    }

    @ApiOperation(value = "单个图片转文本")
    @ResponseBody
    @PostMapping("/singleImage2Text")
    public String singleImage2Text(@RequestBody RequestDTO requestDTO){
        try {
            File sourceFile = new File(requestDTO.getFilePath());
            SpirePdfUtil image2Text = new SpirePdfUtil();
            String result = image2Text.image2Txt(sourceFile);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常，则告诉页面失败
            return "转换失败";
        }
    }

    @ApiOperation(value = "视频转音频")
    @ResponseBody
    @PostMapping("/video2Audio")
    public String video2Audio(@RequestBody RequestDTO requestDTO){
        try {
            //注意是路径+文件名
            File sourceFile = new File(requestDTO.getFilePath());
            Video2AudioUtil video2Audio = new Video2AudioUtil();
            String targetFilePath = video2Audio.video2Audio(requestDTO.getFilePath(), video2Audio.getTarget(requestDTO.getFilePath()));
            //告诉页面上传成功了
            return  targetFilePath;
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常，则告诉页面失败
            return "转换失败";
        }
    }

}
